package com.rfid.a252robot.activity;

import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.rfid.a252robot.R;
import com.rfid.a252robot.activity.presenter.BookInfoPresenter;
import com.rfid.a252robot.activity.view.IBookInfoView;
import com.rfid.a252robot.base.BaseActivity;
import com.rfid.db.bean.Book;
import com.rfid.util.Util;

import butterknife.BindView;
import butterknife.ButterKnife;

public class BookInfoActivity extends BaseActivity<BookInfoPresenter> implements IBookInfoView {
    @Override
    public BookInfoPresenter getPresenter() {
        return new BookInfoPresenter();
    }

    public static void startActivity(Context context,String barcode,String reader) {
        Intent intent = new Intent();
        intent.putExtra("barcode",barcode);
        intent.putExtra("reader",reader);
        intent.setClass(context,BookInfoActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.bookName)
    TextView mBookNameView;
    @BindView(R.id.barcode)
    TextView mBarcodeView;
    @BindView(R.id.bookLocation)
    TextView mBoxTipView;
    @BindView(R.id.image)
    ImageView mCoverView;
    @BindView(R.id.summay)
    TextView mSummay;
    @BindView(R.id.authorsummay)
    TextView mAuthoSummay;

//    @BindView(R.id.open_bt)
//    Button mOpenBt;

    Book mBook;
    String mReader;

    PopupWindow mDialog;
    PopupWindow mInputPopupWindow;
    CountDownTimer mDownTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_info);
        ButterKnife.bind(this);
        String barcode = getIntent().getStringExtra("barcode");
//        mReader = getIntent().getStringExtra("reader");
        mBook = mPresenter.getBook(barcode);
        if (mBook == null) {
            finish();
            return;
        }
        mBookNameView.setText(mBook.getName() + "");
        mBarcodeView.setText(mBook.getBarcode() + "");
        mBoxTipView.setText(String.format("书籍位置：%s号柜",Util.getBoxShow(mBook.getBoxNum())));
//        if (TextUtils.isEmpty(mReader)) {
//            mOpenBt.setEnabled(false);
//        }

        setRightView(R.mipmap.icon_home, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(BookInfoActivity.this,MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        });
        Glide.with(this).load(Util.getCover(mBook.getIsbn()))
                .placeholder(R.mipmap.default_cover)
                .into(mCoverView);

        mPresenter.getBookInfo(mBook.getIsbn());
    }

    @Override
    protected int getCountDownTime() {
        return 70000;
    }

    @Override
    protected void onTimeTick(long millisUntilFinished) {
    }

    @Override
    protected int getWaitTime() {
        return 60000;
    }

    public void borrow(View v) {
        showLoginTypeDialog();
    }

    private void showLoginTypeDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_login_type,null);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("请选择登录方式")
                .setView(view)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        dialog.show();
        view.findViewById(R.id.input_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUserInputDialog(null);
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.scan_qr).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showQrScanPopwindow();
                dialog.dismiss();
            }
        });
    }

    private void showUserInputDialog(String readerId) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_reader_pwd_input, null);
        PopupWindow popupWindow =new PopupWindow(view, metrics.widthPixels, Util.getScreenHeight(), true);
        mInputPopupWindow = popupWindow;
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x33000000));
        popupWindow.setTouchable(true);
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        uiFlags |= 0x00001000;
        popupWindow.getContentView().setSystemUiVisibility(uiFlags);
        popupWindow.setSoftInputMode(SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        popupWindow.setFocusable(false);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(findViewById(R.id.parent), Gravity.LEFT,0,0);
        popupWindow.setFocusable(true);
        popupWindow.update();
        View quit = view.findViewById(R.id.quit);
        EditText reader = view.findViewById(R.id.reader);
        if (!TextUtils.isEmpty(readerId)) {
            reader.setText(readerId);
            reader.setEnabled(false);
        }
        TextView title = view.findViewById(R.id.ht);
        EditText pwd = view.findViewById(R.id.pwd);
        Button button = view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String passWord = pwd.getText().toString();
                if (TextUtils.isEmpty(readerId)) {
                    String readerId = reader.getText().toString();
                    if (TextUtils.isEmpty(readerId)) {
                        Toast.makeText(BookInfoActivity.this,"读者证不能为空",Toast.LENGTH_SHORT).show();
                        return;
                    } else if (TextUtils.isEmpty(passWord)) {
                        Toast.makeText(BookInfoActivity.this,"密码不能为空",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    title.setText("正在登录，请稍后");
                    button.setEnabled(false);
                    doLogin(readerId,passWord);
                } else {
                    title.setText("正在登录，请稍后");
                    button.setEnabled(false);
                    doLogin(readerId,passWord);
                }
            }
        });
        quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        if (TextUtils.isEmpty(readerId)) {
            reader.requestFocus();
        } else {
            pwd.requestFocus();
        }

    }

    private void doLogin(String readerId, String passWord) {
        mPresenter.login(readerId,passWord,mBook.getBoxNum());
    }

    private void showQrScanPopwindow() {
        if (mDialog != null && mDialog.isShowing()) {
            return;
        }
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_borrow_layout, null);
        mDialog =new PopupWindow(view, metrics.widthPixels, Util.getScreenHeight(), true);
        mDialog.setBackgroundDrawable(new ColorDrawable(0x33000000));
        mDialog.setTouchable(true);
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        uiFlags |= 0x00001000;
        mDialog.getContentView().setSystemUiVisibility(uiFlags);
        mDialog.setFocusable(false);
        mDialog.showAtLocation(findViewById(R.id.parent), Gravity.LEFT,0,0);
        TextView ct = view.findViewById(R.id.ct);
        View cancel = view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPresenter.stopScanQr();
                mDownTimer.cancel();
            }
        });
        mDownTimer = new CountDownTimer(60000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                ct.setText("" + millisUntilFinished/1000);
            }

            @Override
            public void onFinish() {
                mDialog.dismiss();
            }
        };
        mDownTimer.start();
        mPresenter.startScanQr();
    }

    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void onLoginSuccess(String readerId, String pwd) {
        mReader = readerId;
        mPresenter.stopScanQr();
        if (mDialog != null) {
            mDialog.dismiss();
        }
        if (mInputPopupWindow != null) {
            mInputPopupWindow.dismiss();
        }
        if (mBook != null) {
            BorrowActivity.startActivity(this, readerId, pwd,mBook.getBoxNum());
            finish();
        }
    }

    @Override
    public void onLoginFail(String reason) {
        Toast.makeText(this,reason,Toast.LENGTH_SHORT).show();
        if (mInputPopupWindow != null&&mInputPopupWindow.isShowing()) {
            View view = mInputPopupWindow.getContentView();
            view.findViewById(R.id.button).setEnabled(true);
            TextView title = view.findViewById(R.id.ht);
            title.setText(reason);
        }
    }

    @Override
    public void onScanResult(String qr) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        showUserInputDialog(qr);
    }

    @Override
    public void onIntroInfo(String message, String amsg) {
        if (message != null) {
            mSummay.setText(message);
        }
        if (amsg != null) {
            mAuthoSummay.setText(amsg);
        }
    }

}
